﻿using ClientDemo.Models;
using ClientDemo.Services;
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientDemo
{
    public partial class Form1 : Form
    {
        private HubConnection _hubConnection;
        private readonly string _clientId = Guid.NewGuid().ToString();
        public Form1()
        {
            InitializeComponent();
        }
        private async void InitializeSignalR()
        {
            _hubConnection = new HubConnectionBuilder()
                .WithUrl(txtUrl.Text.Trim())
                .Build();

            //接收webapi回传的要解析的内容
            _hubConnection.On<string>("ReceiveNotification", (message) =>
            {
                this.Invoke((MethodInvoker)delegate {
                    txtNotifications.AppendText($"{DateTime.Now}: {message}{Environment.NewLine}");
                });
            });

            try
            {
                await _hubConnection.StartAsync();
                await _hubConnection.InvokeAsync("Subscribe", _clientId);
                txtNotifications.AppendText("SignalR 连接已建立，客户端ID: " + _clientId + Environment.NewLine);
            }
            catch (Exception ex)
            {
                txtNotifications.AppendText($"连接错误: {ex.Message}" + Environment.NewLine);
            }
        }

        protected override async void OnFormClosing(FormClosingEventArgs e)
        {
            if (_hubConnection != null)
            {
                await _hubConnection.DisposeAsync();
            }
            base.OnFormClosing(e);
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            InitializeSignalR();
            (sender as Button).Enabled = false;
            buttonRequest.Enabled = true;
        }

        //发送webapi请求
        private async void buttonRequest_Click(object sender, EventArgs e)
        {
            RecipeSelectRequest entity = new RecipeSelectRequest();
            entity.messageId = _clientId;
            entity.recipe = new Recipe();
            entity.recipe.name = "发送webapi请求" + DateTime.Now.ToString();
            entity.recipe.version = "1.0";
            var response = await WebManager.RecipeSelectRequestAsync<RecipeSelectResponse>(entity);
        }
    }
}
